
import Vue from 'vue';
import store from '../store';

// let apiUrl = "http://39.100.62.29:9922";
let apiUrl = uni.getStorageSync("baseUrl") || store.state.baseUrl; 
// Vue.prototype.$apiUrl = apiUrl;
// import Qs from "qs";
Vue.prototype.$getApi = function(url, data, callsuc, token,err) {
	data = data ? data : {};
	let userInfo = store.state.userInfo; 
	// uni.showLoading();
	
	let header = {
		'content-type': 'application/x-www-form-urlencoded',
		// 'content-type': 'application/json',
		// "Access-Control-Allow-Origin":"*"
	}
	uni.request({
		url: apiUrl + "/api.php"+ url,
		method: 'post',
		data: data,
		header,
		success: (res) => {
			// uni.hideLoading();
			console.log(res)
			err instanceof Function && err(res.data);
			if (res.data.code == 1) {
				callsuc instanceof Function && callsuc(res.data);
				// if(res.data.msg){
				// 	this.$msg(res.data.msg)
				// }
			} else
			if (res.data.code == 0) {
				try{
					// uni.hideLoading();
				}catch(e){
					//TODO handle the exception
				}
				if(res.data.msg.indexOf("已领取过该优惠券") != -1){
					uni.setStorageSync('lingquQ',1)
				}
				if(res.data.msg.indexOf("token is error") !=  -1 ){
					uni.reLaunch({
						url:"/pages/login/login"
					})
				}else{
					this.$msg(res.data.msg)
				}
				return false
			} else
			if (res.data.code == 401) {
				this.$msg("请重新登录")
				// #ifndef MP
					this.$store.commit("logout");
					uni.reLaunch({
						url:"/pages/login/login"
					})
				// #endif
				// #ifdef MP
					this.$store.commit("logout");
					setTimeout(()=>{
						uni.switchTab({
							url: '../../pages/home/home'
						})
					},1000)
				// #endif
			} else
			if (res.data.code == 402) {
				this.$msg(res.data.msg)
			} else
			if (res.data.code == 403) {
				this.$msg(res.data.msg)
				callsuc instanceof Function && callsuc(res.data);
			} 
		},
		fail: (err) => {
			this.$msg("网络请求出错")
			
			setTimeout(()=>{
				// uni.hideLoading();
				uni.reLaunch({
					url:"/pages/login/noData"
				})
			},4000)
			
			
		}
	});
}
Vue.prototype.$postApi = function(url, data, callsuc, token,ccid,err) {
	data = data ? data : {};
	let userInfo = store.state.userInfo; 
	// uni.showLoading();
	
	let header = {
		'content-type': 'application/x-www-form-urlencoded',
	}
	if(!token){
		data.token = userInfo.token
	}else
	if(token == "false"){}
	else{
		data.token = token
	}
	
	uni.request({
		url: apiUrl + "/api"+ url,
		method: 'post',
		data:data,
		header: header,
		// multipart/form-data
		success: (res) => {
			err instanceof Function && err(res.data);
			if (res.data.code == 1) {
				callsuc instanceof Function && callsuc(res.data);
				// if(res.data.msg){
				// 	this.$msg(res.data.msg)
				// }
			} else
			if (res.data.code == 0) {
				try{
					// uni.hideLoading();
				}catch(e){
					//TODO handle the exception
				}
				if(res.data.msg.indexOf("已领取过该优惠券") != -1){
					uni.setStorageSync('lingquQ',1)
				}
				if(res.data.msg.indexOf("token is error") !=  -1 ){
					uni.reLaunch({
						url:"/pages/login/login"
					})
				}else{
					this.$msg(res.data.msg)
				}
				return false
			} else
			if (res.data.code == 401) {
				this.$msg(res.data.msg)
				// #ifndef MP
					this.$store.commit("logout");
					setTimeout(()=>{
						uni.reLaunch({
							url:"/pages/login/login"
						})
					},1000)
					
				// #endif
				// #ifdef MP
					this.$store.commit("logout");
					setTimeout(()=>{
						uni.switchTab({
							url: '../../pages/home/home'
						})
					},1000)
				// #endif
			} else
			if (res.data.code == 402) {
				this.$msg(res.data.msg)
			} else
			if (res.data.code == 403) {
				this.$msg(res.data.msg)
				callsuc instanceof Function && callsuc(res.data);
			}  
		},
		fail: (err) => {
			this.$msg("网络请求出错")
		}
	});
}
Vue.prototype.$resetUserInfo = function(back) {
	console.log(this.$store.state.userInfo,"this.$store.state.userInfo")
	this.$getApi("/user/userInfo",{},res1=>{
		let userinfo = {
			...res1.data,
			token:this.$store.state.userInfo.token
		}
		console.log(res1)
		this.$store.commit("login",userinfo)
		back instanceof Function  && back(userinfo)
	})
}
Vue.prototype.$getApiTime = function(url, data, callsuc, token) {
	token = token == "false" ? false : true;
	data = data ? data : {};
	console.log("token", token);
	let userInfo = uni.getStorageSync('userInfo');
	if (token && userInfo) {
		data.token = userInfo.remember_token;
		data.page = 1;
		data.paginate = 200;
	}
	uni.request({
		url: apiUrl + url,
		method: 'post',
		data: data,
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		success: (res) => {
			console.log(res)
			if (res.data.status == 200 || res.data.status == 202) {
				// this.$msg(res.data.msg)
				callsuc instanceof Function && callsuc(res.data)
			} else
			if (res.data.status == 401) {
				this.$msg("登录已过期,请重新登录")
				// #ifndef MP
					this.$store.commit("logout");
					uni.reLaunch({
						url: '../login/yLogin',
						success(){
							// location.reload()
						}
					})
				// #endif
				// #ifdef MP
					this.$store.commit("logout");
					callsuc instanceof Function && callsuc(res.data)
					
				// #endif
			}
		},
		fail: (err) => {
			this.$msg("网络错误,请联系管理员")
		}
	});
}

Vue.prototype.$store = store;

const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	title = title || "请输入完整信息";
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
Vue.prototype.$msg = msg;

const getDate = (myDate,type,timec) => {
	if(!myDate){
		myDate = new Date()
	}else{
		if(timec == "c"){
			myDate = new Date(parseInt(myDate) * 1000)
		}else{
			myDate = new Date(myDate)
		}
	}
	let year = myDate.getFullYear();   //获取系统的年；
	let month = myDate.getMonth()+1;   //获取系统月份，由于月份是从0开始计算，所以要加1
	
	let date = myDate.getDate(); // 获取系统日，
	
	let hours = myDate.getHours(); //获取系统时，
	let min = myDate.getMinutes(); //分
	let sec = myDate.getSeconds(); //秒
	if(month<10){ month = "0"+month}
	if(date<10){ date = "0"+date }
	if(hours<10){ hours = "0"+hours}
	if(min<10){ min = "0"+min}
	if(sec<10){ sec = "0"+sec }
	
	if(type == '月-号'){
		return month+'月'+date+'号'
	}else
	if(type == '年-月-日'){
		return year+'年'+month+'月'+date+'日'
	}else
	if(type == 's-s-s'){
		return year+'-'+month+'-'+date
	}else
	if(type == 's:s:s'){
		return hours+':'+min+':'+sec
	}else
	if(type == 's-s-s s:s:s'){
		return year+'-'+month+'-'+date+" "+hours+':'+min+':'+sec
	}else{
		return year+'-'+month+'-'+date+" "+hours+':'+min+':'+sec
	}
}
Vue.prototype.$getDate = getDate;
const lastDate = (myDate,type) => {
	var date = new Date();
	var now = date.getTime();
	var str= myDate;
	var endDate = new Date(str);
	var end = endDate.getTime();
	var leftTime = end-now; 
	var d,h,m,s;
	d = Math.floor(leftTime/1000/60/60/24);
	h = Math.floor(leftTime/1000/60/60%24);  
	m = Math.floor(leftTime/1000/60%60);  
	s = Math.floor(leftTime/1000%60);
	if(h<10){ h = "0"+h}
	if(m<10){ m = "0"+m}
	if(s<10){ s = "0"+s}
	if (leftTime>=0) {  
		if(type == 'd-s:s:s'){
			if(d == 0){
				if(h == '00'){
					return m+":"+s
				}else{
					return h+":"+m+":"+s
				}
			}else{
				return d+"天" +h+":"+m+":"+s
			}
			
		}else{
			return h+":"+m+":"+s
		}
	} else{
		return "00:00:00"
	}
}
Vue.prototype.$lastDate = lastDate;

Vue.prototype.$shengyuTime = function(val){
	val =Math.ceil(val/1000); 
    let str = "",

    day,

    hour,

    minute,

    seconds;

    if (val > 0) {

        day = Math.floor(val / 60 / 60 / 24) || 0;

        hour = Math.floor((val - day * 3600 * 24) / 60 / 60) || 0;

        minute = Math.floor((val - day * 3600 * 24 - hour * 3600) / 60) || 0;

        seconds = Math.floor(val - day * 3600 * 24 - hour * 3600 - minute * 60) || 0;

        // str += `${day}天` + `${hour}时` + `${minute}分` + `${seconds}秒`;
		if(hour<10){ hour = "0"+hour}
		if(minute<10){ minute = "0"+minute}
		if(seconds<10){ seconds = "0"+seconds }
		
        return  [day,hour,minute,seconds]

    } else {

        return ["00","00","00"]

    }

}

Vue.prototype.$calcPhone = function(el){
	if(el){
		return el.substr(0,3) + "****" + el.substr(7)
	}else{
		return "未绑定手机号"
	}
}

Vue.prototype.$qianweifu = function(num){
	num=num.toString().split(".");  // 分隔小数点
	    var arr=num[0].split("").reverse();  // 转换成字符数组并且倒序排列
	    var res=[];
	    for(var i=0,len=arr.length;i<len;i++){
	      if(i%3===0&&i!==0){
	         res.push(",");   // 添加分隔符
	      }
	      res.push(arr[i]);
	    }
	    res.reverse(); // 再次倒序成为正确的顺序
	    if(num[1]){  // 如果有小数的话添加小数部分
	      res=res.join("").concat("."+num[1]);
	    }else{
	      res=res.join("");
	    }
	    return res;
}

Vue.prototype.$daojishi = function(time,time2){
	let nowTimec = new Date();
	if(time){
		nowTimec = new Date(time);
	}
	let nowTime = nowTimec.getTime();
	var setDate = new Date(time2);
	var setTime = setDate.getTime(); //设定的时间

	//获取剩余时间总秒数
	var getTimes = (setTime - nowTime) / 1000;

	//获取天数
	var d = parseInt(getTimes / 60 / 60 / 24);
	d = d < 10 ? '0' + d : d;

	//获取小时
	var h = parseInt(getTimes / 60 / 60 % 24);
	h = h < 10 ? '0' + h : h;

	//获取分钟
	var m = parseInt(getTimes / 60 % 60);
	m = m < 10 ? '0' + m : m;

	//获取秒数
	var s = parseInt(getTimes % 60);
	s = s < 10 ? '0' + s : s;
	if(nowTime >= setTime){
		return ["00","00","00"]
	}else{
		return  [h,m,s];
	}
	

}